package com.web.wrapper;

import org.apache.log4j.Logger;

import com.google.common.base.Charsets;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.hash.Hashing;
import com.web.util.RbdRemovalListerner;
import com.web.util.util;
import com.web.wrapper.hood.CephRBDAccessor;

public final class CephAccessorFactory {
	private static int DEFAULT_CACHE_SIZE =100 ;
	private static Logger logger = Logger.getLogger(CephAccessorFactory.class) ;
	//cache the Ceph socket connection 
	//caching just for reusing of connections ,if not proper ,get rid of it
	private static Cache<String, Object> cache = CacheBuilder
									.newBuilder()
									.maximumSize(DEFAULT_CACHE_SIZE)
									.concurrencyLevel(DEFAULT_CACHE_SIZE/10)
									.removalListener( new RbdRemovalListerner())
									.build() ;
	
	private CephAccessorFactory(){}
	public static void setCephOp(String key,Object value ){
		cache.put(key, value);
	}
	/**
	 * the key is relative with the session
	 * @param key user name
	 * @param pool
	 * @return
	 * @throws Exception 
	 */
	public static CephRBDAccessor getRbd( String key,String pool) throws Exception{
		util.nullCheck(pool);
		key = getRbdKey(key,pool) ;
		Object val = cache.getIfPresent(key) ;
		if( null == val ){
			val = new CephRBDAccessor(pool) ;
			setCephOp(key, val);
		}else{
			logger.debug("cache hit "+key);
		}
		return (CephRBDAccessor) cache.getIfPresent(key) ;
	}
	
	/**
	 * distinguish the rbd with rados
	 */
	public static String getRbdKey(String key,String pool){
		String input = key+":"+pool  ;
		int hash = Hashing.murmur3_32().hashString(input, Charsets.UTF_8).asInt() ;
		return "rbd_"+hash;
	} 
	
	public static void main(String[] args) {
		String input =  "nature01:test"   ;
		int hash = Hashing.murmur3_32().hashString(input, Charsets.UTF_8).asInt() ;
		System.out.println( "rbd_"+hash);
	}
	 
}
